package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-14 16:38
 */
public class UserInterceptor implements HandlerInterceptor {

    //拦截器主要对controller增强
    // 拦截器preHandle -> controller方法
    //return true controller方法正常执行 return false结束了，不执行controller方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.解析用户id放到threadlocal

        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)){
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));

            WmThreadLocalUtil.setUser(wmUser);
        }

        return true;
    }

    //controller方法正常执行 ->postHandle
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //不管任何情况，都在最后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //2.清理threadlocal中数据
        WmThreadLocalUtil.clear();
    }
}
